
function printUsage() {
    console.log("Usage: node practice/calc.js <expression>");
    console.log("Examples:");
    console.log("  node practice/calc.js \"1 + 2 * 3\"");
    console.log("  node practice/calc.js 1 + 2");
    console.log("  node practice/calc.js 10/(2+3)");
}

const userArgs = process.argv.slice(2);

if (userArgs.length === 0) {
    printUsage();
    process.exit(0);
}

if (userArgs[0] === "--help" || userArgs[0] === "-h") {
    printUsage();
    process.exit(0);
}

const argsToUse = userArgs.slice(0, 3);
const expression = argsToUse.join(" ").trim();

if (!expression) {
    console.error("Error: Missing expression.");
    printUsage();
    process.exit(1);
}

const validPattern = /^[0-9\s+\-*/().%]+$/;
if (!validPattern.test(expression)) {
    console.error("Error: Invalid expression. Only numbers and + - * / % ( ) . are allowed.");
    process.exit(1);
}

let result;
try {
    result = Function("return (" + expression + ")")();
    if (typeof result !== "number" || Number.isNaN(result)) {
        throw new Error("Expression did not evaluate to a number");
    }
} catch (err) {
    console.error("Error: Failed to evaluate expression.\nDetails:", err.message);
    process.exit(1);
}

console.log("Expression: %s", expression);
console.log("Result: %d", result);